package com.change.zh.ffmpegdo.controller;

import com.change.zh.ffmpegdo.config.StreamPlayYml;
import com.change.zh.ffmpegdo.push.FFmpegManager;
import com.change.zh.ffmpegdo.push.JobDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class MediaController {


    @Autowired
    private StreamPlayYml streamPlayYml;

    @GetMapping(value = {"/", "/index"})
    public String index(Model model) {
        Map<String, String> lives = new HashMap<>();
        //-------
        FFmpegManager fFmpegManager = new FFmpegManager();
        Collection<JobDetail> list = fFmpegManager.queryAll();
        Iterator<JobDetail> iter = list.iterator();
        JobDetail jobDetail = null;
        while (iter.hasNext()) {
            jobDetail = iter.next();
            lives.put(jobDetail.getRoom(), jobDetail.getType());
        }
        model.addAttribute("menu", "直播地址列表");
        model.addAttribute("lives", lives);
        return "/index";
    }

    @GetMapping(value = "/media/menu")
    public String menu(Model model) {
        Map<String, String> lives = new HashMap<>();
        //-------
        FFmpegManager fFmpegManager = new FFmpegManager();
        Collection<JobDetail> list = fFmpegManager.queryAll();
        Iterator<JobDetail> iter = list.iterator();
        JobDetail jobDetail = null;
        while (iter.hasNext()) {
            jobDetail = iter.next();
            lives.put(jobDetail.getRoom(), jobDetail.getType());
        }
        model.addAttribute("menu", "直播地址列表");
        model.addAttribute("lives", lives);
        return "/media/menu";
    }

    @GetMapping("/media/rtmp")
    public String rtmp(Model model, @RequestParam(value = "roomid") String roomid, @RequestParam(value = "roomtype") String roomtype) {
        String src = roomtype.equals("hls")
                ? "http://" + streamPlayYml.getWeb().getIp() + ":" + streamPlayYml.getNginx().getWebport() + "/" + streamPlayYml.getNginx().getHlsname() + "/" + roomid + ".m3u8"
                : "rtmp://" + streamPlayYml.getWeb().getIp() + ":" + streamPlayYml.getNginx().getPort() + "/" + streamPlayYml.getNginx().getLivename() + "/" + roomid;
        String type = roomtype.equals("hls") ? "application/x-mpegURL" : "rtmp/flv";
        model.addAttribute("roomid", roomid);
        model.addAttribute("roomsrc", src);
        model.addAttribute("roomtype", type);
//        return "/media/" + (roomtype.equals("hls") ? "hls" : "rtmp");
        return "/media/media";
    }


}
